package com.dreamlike.loomdemo;

import net.bytebuddy.dynamic.DynamicType;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.Ordered;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;

public class LoomControllerBeanPostProcessor implements BeanPostProcessor , Ordered {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (isRestController(bean)){
            return wrapLoom(bean);
        }
        return BeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
    }
    private boolean isRestController(Object o){
        return o.getClass().getAnnotation(RestController.class) != null;
    }
    private Object wrapLoom(Object o){
        final ControllerInterceptor interceptor = new ControllerInterceptor(o);
        try {
            final DynamicType.Unloaded unloaded = ProxyGenerator.copyMethod(o.getClass(), interceptor).make();
            unloaded.saveIn(new File("ByteClass"));
            return unloaded.load(getClass().getClassLoader()).getLoaded().newInstance();
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }


    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }
}
